package com.jshoperxms.controller.api.pay;

import com.jshoperxms.components.wechat.pay.WXPayConfigImpl;
import com.jshoperxms.components.wechat.pay.WXPayConstants;
import com.jshoperxms.components.wechat.pay.WXPayUtil;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.PrimaryKey;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.OrderEnums;
import com.jshoperxms.controller.utils.enums.YdEnums;
import com.jshoperxms.controller.utils.maths.Arith;
import com.jshoperxms.entity.OrderLdgiftT;
import com.jshoperxms.entity.PayLdgiftamountT;
import com.jshoperxms.entity.SysPayRdT;
import com.jshoperxms.service.OrderLdgiftTService;
import com.jshoperxms.service.PayLdgiftamountTService;
import com.jshoperxms.service.SysPayRdTService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by sdywcd on 2019/12/15.
 * Des:
 */
@RestController
@RequestMapping("/api/wechatpay")
public class WechatPayNotifyCtr {


    @Resource
    private SysPayRdTService sysPayRdTService;

    @Resource
    private PayLdgiftamountTService payLdgiftamountTService;

    @Resource
    private OrderLdgiftTService orderLdgiftTService;

    private WXPayConfigImpl payConfig;

    public WechatPayNotifyCtr() throws Exception {
        payConfig = WXPayConfigImpl.getInstance();
    }


    /**
     * 微信支付回调函数
     * @param request
     * @param response
     */
    @Transactional(rollbackOn=Exception.class)
    @RequestMapping(value = "/notify")
    public void responseWeChat(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //读取参数
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();
        String xmlString = sb.toString();
        Map<String, String> resultData = WXPayUtil.xmlToMap(xmlString);
        // 1.通知参数
        String result_code = resultData.get("result_code");
        String out_trade_no = resultData.get("out_trade_no");
        String return_code = resultData.get("return_code");
        String return_msg = resultData.get("return_msg");
        String attach = resultData.get("attach");
        String transaction_id=resultData.get("transaction_id");
        String resXml = "";
        if (return_code.equals("SUCCESS") && result_code.equals("SUCCESS")) {
            if (WXPayUtil.isSignatureValid(resultData, payConfig.getKey())) {
                if (StringUtils.equals(attach, YdEnums.PAYBUSTYPE.PAYFORTEAMARTICLE.getState())) {
                    //给小队文章打赏业务
                    //1,更新朗读礼物订单状态到已经支付和确认订单成功
                    OrderLdgiftT orderLdgiftT = this.orderLdgiftTService.findByPK(OrderLdgiftT.class, out_trade_no);
                    if (orderLdgiftT != null) {
                        if(StringUtils.isBlank(orderLdgiftT.getTradenumber())){
                            orderLdgiftT.setPaystatus(OrderEnums.OrderPayState.ORDERPAYSTATE_HAVEPAY_ONE_NUM.getState());
                            orderLdgiftT.setOrderstatus(OrderEnums.OrderStatus.ORDERSTATE_SUCCESS_NINE_NUM.getState());
                            orderLdgiftT.setTradenumber(transaction_id);
                            orderLdgiftT.setUpdatetime(DateTools.getSystemTimeBi());
                            orderLdgiftT.setVersiont(orderLdgiftT.getVersiont() + 1);
                            this.orderLdgiftTService.update(orderLdgiftT);

                            //2，朗读礼物打赏总金额表更新礼物支付总金额和次数
                            List<PayLdgiftamountT> payLdgiftamountTList=this.payLdgiftamountTService.findAll(PayLdgiftamountT.class, BaseEnums.DataUsingState.USING.getState());
                            if(!payLdgiftamountTList.isEmpty()){
                                PayLdgiftamountT payLdgiftamountT=payLdgiftamountTList.get(0);
                                payLdgiftamountT.setAmount(BigDecimal.valueOf(Arith.add(payLdgiftamountT.getAmount().doubleValue(),orderLdgiftT.getAmount().doubleValue())));
                                payLdgiftamountT.setPaytimes(payLdgiftamountT.getPaytimes()+1);
                                payLdgiftamountT.setUpdatetime(DateTools.getSystemTimeBi());
                                this.payLdgiftamountTService.update(payLdgiftamountT);
                            }

                            //3,在系统支付中增加支付记录
                            SysPayRdT sysPayRdT = new SysPayRdT();
                            sysPayRdT.setId(PrimaryKey.get().toString());
                            sysPayRdT.setMemberid(orderLdgiftT.getMemberid());
                            sysPayRdT.setAmount(orderLdgiftT.getAmount());
                            sysPayRdT.setCreatetime(DateTools.getSystemTimeBi());
                            sysPayRdT.setUpdatetime(DateTools.getSystemTimeBi());
                            sysPayRdT.setStatus(BaseEnums.DataUsingState.USING.getState());
                            sysPayRdT.setVersiont(1);
                            sysPayRdT.setOuttradeno(out_trade_no);
                            sysPayRdT.setTradetype("wechatpay");
                            sysPayRdT.setBustype(YdEnums.PAYBUSTYPE.PAYFORTEAMARTICLE.getState());
                            sysPayRdT.setNote("这是给小队文章的打赏业务");
                            this.sysPayRdTService.save(sysPayRdT);

                            //4,把打赏的金额加入到被打赏会员的朗读钱包里pay_ldwallet_trade_rd_t pay_ldwallet_t
                        }



                    }


                }
            } else {
                resXml = setXml(WXPayConstants.FAIL, "签名失败");
            }
        } else {
            resXml = setXml(WXPayConstants.FAIL, "参数格式校验错误");
        }
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();

    }

    /**
     * 通过xml 发给微信消息
     *
     * @param return_code
     * @param return_msg
     * @return
     */
    public static String setXml(String return_code, String return_msg) {
        SortedMap<String, String> parameters = new TreeMap<>();
        parameters.put("return_code", return_code);
        parameters.put("return_msg", return_msg);
        return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";

    }
}
